from fastapi import FastAPI
import pymongo
from elasticsearch import Elasticsearch
import gridfs
import bson


client = pymongo.MongoClient('host.docker.internal:27017')
client.admin.authenticate('root', '^&*yt345', mechanism='SCRAM-SHA-1')
books_collection = client.testdb.books
fs = gridfs.GridFS(client.testdb, 'epub')

es = Elasticsearch(
    ['host.docker.internal:9200'],
    http_auth=('elastic', 'changeme')
)

app = FastAPI()


@app.get("/")
async def root():
    return {"message": "Hello World"}


@app.get("/books/{page}")
async def books(page: int):
    # 这样不好,应该有读取上限,应该关闭游标
    re = list(books_collection.find({}, {'_id': 0}))
    return re


@app.get("/books/{key}/{page}")
async def books_search(key: str, page: int):
    dsl = {
        'query': {
            'match': {
                'content': key
            }
        }
    }
    # 同样不好
    hits = es.search(index='testindex', body=dsl, filter_path=[
        'hits.hits._source.title', 'hits.hits._source.id'])
    print(hits)
    if 'hits' not in hits.keys():
        return []
    hits = hits['hits']['hits']
    re = []
    for s in hits:
        re.append(books_collection.find_one(
            {'_id': bson.ObjectId(s["_source"]['id'])}, {'_id': 0}))
    return re


# uvicorn main:app --port 8000 --host 0.0.0.0
